import strRegisterHtml from "./Register.html";
import { DomUtils } from "../../utils/DomUtils";
import { AccountService } from "../../services/AccountService"; // 引入账户服务

export class Register {
  constructor() {
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  render() {
    const dom = DomUtils.convertToDom(strRegisterHtml);
    // 添加DOM结构检查
    console.debug("Rendered DOM:", dom.outerHTML);
    this.bindEvents(dom);
    return dom;
  }

  bindEvents(dom) {
    const registerButton = dom.querySelector("#registerButton");
    if (!registerButton) {
      console.error(
        "按钮元素查找失败，可用按钮列表：",
        dom.querySelectorAll("button")
      );
      return;
    }
    registerButton.addEventListener("click", (e) => {
      console.log("按钮点击事件触发");
      this.handleSubmit(e, dom);
    });
  }

  validateForm(dom) {
    const getValue = (id) => dom.querySelector(id).value.trim();
    const isChecked = (id) => dom.querySelector(id).checked;

    // 获取表单值
    const username = getValue("#frist_name");
    const email = getValue("#email");
    const password = getValue("#password");
    const passwordConfirm = getValue("#password2");

    // 验证规则
    const validations = [
      [!username, "姓名不能为空"],
      [!email, "邮箱不能为空"],
      [!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email), "邮箱格式不正确"],
      [!password, "密码不能为空"],
      [password.length < 8, "密码至少需要8个字符"],
      [password !== passwordConfirm, "两次输入的密码不一致"],
      [!isChecked("#agree"), "必须接受条款才能注册"],
    ];

    // 查找第一个错误
    const error = validations.find(([condition]) => condition);
    if (error) {
      alert(error[1]);
      return false;
    }
    return true;
  }

  async handleSubmit(event, dom) {
    event.preventDefault();

    if (!this.validateForm(dom)) return;

    // 获取表单数据
    const userData = {
      username: dom.querySelector("#frist_name").value.trim(),
      email: dom.querySelector("#email").value.trim(),
      password: dom.querySelector("#password").value,
    };

    try {
      const result = await AccountService.registerUser(userData);
      alert("注册成功！");
      // 跳转到登录页（根据实际路由配置修改）
      window.location.href = "Login";
    } catch (error) {
      console.error("注册失败:", error);
      alert(`注册失败: ${error.message}`);
    }
  }
}
